import defaultOptions, { ResizeBoxOptionsInt } from "@/js/default";
import { getAction, isString, setClass, addEventListener } from "@/js/utils";
import template from "@/js/template";
import "@/css/resize-box.less";
import {
  EVENT_TOUCH_END,
  EVENT_TOUCH_MOVE,
  EVENT_TOUCH_START,
  CLASS_RESIZE_BOX,
  EVENT_POINTER_DOWN,
  EVENT_POINTER_MOVE,
  EVENT_POINTER_UP,
} from "@/js/constants";
import type { ActionType } from "@/js/constants";
class ResizeBox {
  options: ResizeBoxOptionsInt = defaultOptions;
  action: ActionType | undefined | null;
  element: HTMLElement;
  constructor(element: HTMLElement | string, options?: ResizeBoxOptionsInt) {
    if (isString(element)) {
      element = document.querySelector(element) as HTMLElement;
      if (!element) {
        throw new Error("element is not found");
      }
    }
    this.element = element;
    this.options = Object.assign({}, this.options, options);

    this.init();
  }

  init() {
    let div = document.createElement("div") as HTMLDivElement;
    div.innerHTML = template;
    setClass(this.element, CLASS_RESIZE_BOX);
    div
      .querySelectorAll("span")
      .forEach(this.element.appendChild.bind(this.element));
    div.remove();

    this.bind();
  }

  bind() {
    const touchStart = this.touchStart.bind(this);
    const touchMove = this.touchMove.bind(this);
    const touchEnd = this.touchEnd.bind(this);
    console.log("this.element.ownerDocument-->", this.element.ownerDocument);
    addEventListener(this.element, EVENT_POINTER_DOWN, touchStart);
    addEventListener(this.element.ownerDocument, EVENT_POINTER_MOVE, touchMove);
    addEventListener(this.element.ownerDocument, EVENT_POINTER_UP, touchEnd);
  }

  touchStart(event: Event) {
    const action = getAction(event);
    if (!action) {
      return;
    }
    this.action = action;
    console.log("-->", event.type, action);

    event.preventDefault();
  }

  touchMove(event: Event) {
    const { action } = this;
    if (!action) {
      return;
    }
    console.log(event);
    event.preventDefault();
  }

  touchEnd(event: Event) {
    const { action } = this;

    if (!action) return;
    console.log(event);
    event.preventDefault();
    this.action = void 0;
  }
}

export default ResizeBox;
